<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { updateDictionaryApi, getSuccessStatus } from '@/api/dictionary'

const props = withDefaults(
	defineProps<{
		categoryList?: any[]
		editRow: any
	}>(),
	{
		categoryList: () => [],
	}
)

const formInstance = ref<FormInstance | null>(null)
const initState = {
	categoryName: undefined,
	name: '',
	value: '',
}
const state = ref<ObjType>(initState)
const categoryListOptions = ref<SelectOption[]>([])

const formLayout = {
	style: 'margin: 0 10px',
	labelWidth: 'auto',
	labelPosition: 'left',
}

const rules = {
	categoryName: [{ required: true, message: '请输入字典类别名称！', trigger: 'change' }],
	prop: [{ required: true, message: '请输入字典名称！', trigger: 'change' }],
	value: [{ required: true, message: '请输入字典值！', trigger: 'change' }],
}

async function formCommit() {
	try {
		await formInstance.value?.validate()
		const res = await updateDictionaryApi([{ ...props.editRow, ...state.value }])
		if ((res.code = getSuccessStatus())) {
			return true
		}
	} catch (error) {
		console.log(error)
	}
}

function init() {
	formInstance.value?.resetFields()
	state.value = initState
	categoryListOptions.value = props.categoryList.map((v) => ({ label: v.categoryTitle, value: v.categoryName }))
	Object.keys(state.value).forEach((k) => {
		state.value[k] = props.editRow[k]
	})
}

defineExpose({
	init,
	formCommit,
})
</script>

<template>
	<el-form :model="state" :rules="rules" v-bind="formLayout" ref="formInstance">
		<el-row :gutter="24">
			<el-col :span="24">
				<el-form-item prop="categoryName" label="字典类别">
					<my-select :options="categoryListOptions" v-model="state.categoryName" style="width: 100%" filterable placeholder="请选择字典类别" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item prop="name" label="名称">
					<el-input v-model="state.name" placeholder="请输入字典名称" allowClear />
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item prop="value" label="值">
					<el-input v-model="state.value" placeholder="请输入字典值" allowClear />
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>
